package com.leosam.tvbox.mv.lucene;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PersistentSequenceGenerator {
    private final Logger logger = LoggerFactory.getLogger(PersistentSequenceGenerator.class);
    private int nextId;
    private File file;

    public PersistentSequenceGenerator(String filePath) {
        this.file = new File(filePath);
        this.nextId = readNextIdFromFile();
    }

    public synchronized String next() {
        int id = nextId++;
        saveNextIdToFile(nextId);
        return Integer.toString(id);
    }

    private int readNextIdFromFile() {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line = reader.readLine();
            if (line != null) {
                return Integer.parseInt(line);
            }
        } catch (IOException e) {
            logger.error("read sequence failed", e);
        }
        return 1; // 默认从1开始
    }

    private void saveNextIdToFile(int nextId) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(String.valueOf(nextId));
        } catch (IOException e) {
            logger.error("write sequence failed", e);
        }
    }
}
